<template>
  <div class="stock-page">
    <h1>库存管理</h1>
    <el-card>
      <el-tabs v-model="activeTab" @tab-change="onTabChange">
        <!-- 原料库存分页 -->
        <el-tab-pane label="原料库存" name="material">
          <div style="margin-bottom: 15px; display: flex">
            <el-input v-model="materialSearchQuery" placeholder="输入库存ID(INV开头)或原料ID"
              style="width: 300px; margin-right: 10px" />
            <el-button type="primary" @click="searchMaterial">搜索</el-button>
            <el-button @click="resetMaterialSearch">重置</el-button>
            <!-- 在原料库存tab的搜索按钮旁边添加添加按钮 -->
            <el-button type="success" @click="showAddMaterialDialog">添加原料库存</el-button>
            <!-- 添加原料库存对话框 -->
            <el-dialog v-model="addMaterialDialogVisible" title="添加原料库存" width="30%">
              <el-form :model="addMaterialForm" label-width="120px">
                <el-form-item label="原料ID" required>
                  <el-select 
                    v-model="addMaterialForm.materialId" 
                    placeholder="请选择原料"
                    @change="handleMaterialChange"
                    filterable
                    style="width: 100%">
                    <el-option
                      v-for="item in materialOptions"
                      :key="item.value"
                      :label="`${item.label} (${item.value})`"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="库存数量" required>
                  <el-input-number v-model="addMaterialForm.quantity" :min="0" style="width: 100%" />
                </el-form-item>
                <el-form-item label="单位">
                  <el-input v-model="addMaterialForm.unit" readonly style="width: 80px" />
                </el-form-item>
                <el-form-item label="安全库存">
                  <el-input v-model="addMaterialForm.safetyStock" readonly style="width: 100px" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="addMaterialDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addMaterialStock">确定</el-button>
              </template>
            </el-dialog>
            <!-- 添加修改库存对话框 -->
            <el-dialog v-model="editDialogVisible" title="补充库存数量" width="30%">
              <el-form :model="editForm" label-width="120px">
                <el-form-item label="原料ID">
                  <el-input v-model="editForm.materialId" readonly />
                </el-form-item>
                <el-form-item label="补充数量" required>
                  <el-input-number v-model="editForm.quantity" :min="1" style="width: 100%" />
                </el-form-item>
                <el-form-item label="补充原因" required>
                  <el-input v-model="editForm.reason" type="textarea" placeholder="请输入补充原因" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleReplenish">确定</el-button>
              </template>
            </el-dialog>
          </div>
          <el-table :data="filteredMaterialStocks" v-loading="loading" element-loading-text="数据加载中...">
            <el-table-column prop="id" label="库存ID" width="120" sortable />
            <el-table-column prop="materialId" label="原料ID" width="120" sortable />
            <el-table-column prop="materialName" label="原料名称" sortable />
            <el-table-column prop="quantity" label="库存数量" width="150" align="center" sortable>
              <template #default="{row}">
                <span :style="{color: row.quantity < row.safeStock ? 'red' : 'inherit'}">
                  {{row.quantity}}
                  <el-tag v-if="row.quantity < row.safeStock" type="danger" size="small" style="margin-left: 5px">
                    库存低
                  </el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="safeStock" label="安全库存" width="150" align="center" sortable />
            <el-table-column prop="unit" label="单位" width="100" align="center" sortable />
            <el-table-column prop="updateTime" label="最近更新时间" width="180" sortable />
            <template #empty>
              <div style="padding: 40px; text-align: center; color: #909399;">
                <div style="font-size: 48px; margin-bottom: 16px;">📦</div>
                <div style="font-size: 16px; margin-bottom: 8px;">暂无原料库存数据</div>
                <div style="font-size: 14px;">返回: 库存记录不存在</div>
              </div>
            </template>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button 
                  plain
                  size="small" 
                  @click="showEditDialog(scope.row)"
                  style="margin-right: 10px; background-color: white; border-color: #dcdfe6">
                  补充
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteMaterial(scope.row.id)"
                  :loading="scope.row.deleting">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @current-change="handleMaterialPageChange" :current-page="currentMaterialPage"
            :page-size="pageMaterialSize" :total="totalMaterial" layout="total, prev, pager, next, jumper" background
            style="margin-top: 20px; text-align: left" />
        </el-tab-pane>

        <!-- 产品库存分页 -->
        <el-tab-pane label="产品库存" name="product">
          <div style="margin-bottom: 15px; display: flex">
            <el-input v-model="productSearchQuery" placeholder="输入库存ID(INV开头)或产品ID"
              style="width: 300px; margin-right: 10px" />
            <el-button type="primary" @click="searchProduct">搜索</el-button>
            <el-button @click="resetProductSearch">重置</el-button>
          </div>
          <el-table :data="filteredProductStocks" v-loading="loading" element-loading-text="数据加载中...">
            <el-table-column prop="id" label="库存ID" width="120" sortable />
            <el-table-column prop="productId" label="产品ID" width="120" sortable />
            <el-table-column prop="productName" label="产品名称" sortable />
            <el-table-column prop="wipQuantity" label="在制品数量" width="200" align="center" sortable />
            <el-table-column prop="finishedQuantity" label="完成品数量" width="200" align="center" sortable />
            <el-table-column prop="updateTime" label="最近更新时间" width="180" sortable />
            <template #empty>
              <div style="padding: 40px; text-align: center; color: #909399;">
                <div style="font-size: 48px; margin-bottom: 16px;">📦</div>
                <div style="font-size: 16px; margin-bottom: 8px;">暂无产品库存数据</div>
                <div style="font-size: 14px;">返回: 库存记录不存在</div>
              </div>
            </template>
          </el-table>
          <el-pagination @current-change="handleProductPageChange" :current-page="currentProductPage"
            :page-size="pageProductSize" :total="totalProduct" layout="total, prev, pager, next, jumper" background
            style="margin-top: 20px; text-align: left" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import api, { materialAPI, inventoryAPI } from '@/api'; // 引入统一封装的API模块

const activeTab = ref('material')
const searchQuery = ref('')
const loading = ref(false)

// 产品库存数据
const productStocks = ref([])

// 产品搜索相关变量
const productSearchQuery = ref('')

// 原料搜索相关变量
const materialSearchQuery = ref('')

// 修改产品库存过滤函数
const filteredProductStocks = computed(() => {
  const data = productStocks.value || []
  if (!productSearchQuery.value) return data
  const query = productSearchQuery.value.toLowerCase()
  return data.filter(s => {
    return (s.id && String(s.id).toLowerCase().includes(query)) ||
      (s.productId && String(s.productId).toLowerCase().includes(query)) ||
      (s.productName && String(s.productName).toLowerCase().includes(query))
  })
})

// 修改原料库存过滤函数
const filteredMaterialStocks = computed(() => {
  const data = materialStocks.value || []
  if (!materialSearchQuery.value) return data
  const query = materialSearchQuery.value.toLowerCase()
  return data.filter(s => {
    return (s.id && String(s.id).toLowerCase().includes(query)) ||
      (s.materialId && String(s.materialId).toLowerCase().includes(query)) ||
      (s.materialName && String(s.materialName).toLowerCase().includes(query))
  })
})

// 原料库存数据
const materialStocks = ref([])

// 获取原料库存数据
const fetchMaterialOptions = async () => {
  try {
    loading.value = true
    // 使用统一的API模块
    const response = await materialAPI.getMaterialPage({
      pageNum: 1,
      pageSize: 1000
    })
    
    console.log('原料数据响应:', response.data)
    
    if (response.data.code === 200) {
      // 确保正确映射API返回的字段
      materialOptions.value = response.data.data.records.map(item => ({
        value: item.materialId || item.id,  // 使用materialId或id作为值
        label: item.materialName || item.name,  // 使用materialName或name作为显示文本
        unit: item.unit,
        description: item.description || item.materialDescription,
        safeStock: item.safetyStock || item.safeStock
      }))
      console.log('成功获取原料选项:', materialOptions.value)
    } else {
      console.warn('获取原料数据失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取原料数据失败:', error)
    ElMessage.error(`获取原料数据失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 修改分页相关变量 - 分别维护
const currentProductPage = ref(1)
const pageProductSize = ref(10)
const totalProduct = ref(0)

const currentMaterialPage = ref(1)
const pageMaterialSize = ref(10)
const totalMaterial = ref(0)

// 修改页码变化处理函数
const handleProductPageChange = (val) => {
  currentProductPage.value = val
  fetchProductStocks()
}

const handleMaterialPageChange = (val) => {
  currentMaterialPage.value = val
  fetchMaterialStocks()
}

// 修改获取产品库存数据方法
const fetchProductStocks = async () => {
  try {
    loading.value = true
    const requestData = {
      current: currentProductPage.value,
      size: pageProductSize.value
    }
    // 使用统一的API模块
    const response = await inventoryAPI.product.getPage(requestData)

    if (response.data.success === true || response.data.code === 200) {
      let records = []
      // 尝试不同的数据结构
      if (response.data.data && response.data.data.records) {
        records = response.data.data.records
      } else if (response.data.data && Array.isArray(response.data.data)) {
        records = response.data.data
      } else if (Array.isArray(response.data)) {
        records = response.data
      }

      productStocks.value = records.map(item => ({
        id: item.inventoryId,
        productId: item.productId,
        productName: item.productName,
        wipQuantity: item.wipQuantity || 0,
        finishedQuantity: item.finishedQuantity || 0,
        updateTime: item.lastUpdate || item.updateTime || new Date().toLocaleString()
      }))

      // 设置总数
      // 确保使用API返回的总数而不是records.length
      if (response.data.data && response.data.data.total) {
        totalProduct.value = response.data.data.total
      } else if (response.data.data && response.data.data.totalProduct) {
        totalProduct.value = response.data.data.totalProduct
      } else {
        totalProduct.value = records.length
        console.warn('使用记录长度作为总数:', totalProduct.value)
      }

      console.log('✅ 产品库存获取成功，记录数:', records.length, '总数:', totalProduct.value)
    } else {
      console.warn('产品库存API返回:', response.data.message)
      ElMessage.warning(`产品库存: ${response.data.message || '暂无数据'}`)
      productStocks.value = []
      totalProduct.value = 0
    }
  } catch (error) {
    console.error('获取产品库存失败:', error.message)
    ElMessage.error(`获取产品库存失败: ${error.message}`)
    productStocks.value = []
    totalProduct.value = 0
  } finally {
    loading.value = false
  }
}

// 在获取原料库存数据后调用检查
const fetchMaterialStocks = async () => {
  try {
    loading.value = true
    const requestData = {
      current: currentMaterialPage.value,
      size: pageMaterialSize.value
    }
    // 使用统一的API模块
    const response = await inventoryAPI.material.getPage(requestData)

    // 检查不同的响应格式
    if (response.data.success === true || response.data.code === 200) {
      let records = []
      // 尝试不同的数据结构
      if (response.data.data && response.data.data.records) {
        records = response.data.data.records
      } else if (response.data.data && Array.isArray(response.data.data)) {
        records = response.data.data
      } else if (Array.isArray(response.data)) {
        records = response.data
      }

      materialStocks.value = records.map(item => ({
        id: item.inventoryId,
        materialId: item.materialId,
        materialName: item.materialName,
        quantity: item.quantity,  // 确保这个字段存在且正确
        safeStock: item.safetyStock || item.safeStock,  // 确保至少一个安全库存字段存在
        unit: item.unit,
        updateTime: item.lastUpdate || item.updateTime || new Date().toLocaleString()
      }))

      // 设置总数
      // 确保使用API返回的总数而不是records.length
      if (response.data.data && response.data.data.total) {
        totalMaterial.value = response.data.data.total
      } else if (response.data.data && response.data.data.totalMaterial) {
        totalMaterial.value = response.data.data.totalMaterial
      } else {
        totalMaterial.value = records.length
        console.warn('使用记录长度作为总数:', totalMaterial.value)
      }

      console.log('✅ 原料库存获取成功，记录数:', records.length)
    } else {
      console.warn('原料库存API返回:', response.data.message)
      ElMessage.warning(`原料库存: ${response.data.message || '暂无数据'}`)
      materialStocks.value = []
      totalMaterial.value = 0
    }
  } catch (error) {
    console.error('获取原料库存失败:', error.message)
    ElMessage.error(`获取原料库存失败: ${error.message}`)
    materialStocks.value = []
    totalMaterial.value = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  currentMaterialPage.value = 1  // 修改为使用独立变量
  pageMaterialSize.value = 10    // 修改为使用独立变量
  currentProductPage.value = 1    // 修改为使用独立变量
  pageProductSize.value = 10      // 修改为使用独立变量

  fetchMaterialStocks().catch(e => console.error('初始化失败:', e))
  fetchProductStocks().catch(e => console.error('初始化失败:', e))
})

// 产品搜索方法
const searchProduct = async () => {
  try {
    loading.value = true
    const searchId = productSearchQuery.value.trim()
    if (!searchId) {
      currentProductPage.value = 1  // 重置页码
      fetchProductStocks()
      return
    }

    let response
    if (searchId.startsWith('INV')) {
      response = await inventoryAPI.product.getById(searchId)
    } else {
      response = await inventoryAPI.product.getByProductId(searchId)
    }

    if (response.data.code === 200) {
      const item = response.data.data
      productStocks.value = [{
        id: item.inventoryId,
        productId: item.productId,
        productName: item.productName,
        wipQuantity: item.wipQuantity,
        finishedQuantity: item.finishedQuantity,
        updateTime: new Date().toLocaleString()
      }]
      totalProduct.value = 1
    } else {
      ElMessage.error('未找到匹配的产品库存记录')
      productStocks.value = [] // 清空表格数据
      totalProduct.value = 0
    }
  } catch (error) {
    console.error('未找到匹配的产品库存记录')
    ElMessage.error('产品库存不存在')
    productStocks.value = [] // 清空表格数据
    totalProduct.value = 0
  } finally {
    loading.value = false
  }
}

// 原料搜索方法
const searchMaterial = async () => {
  try {
    loading.value = true
    const searchId = materialSearchQuery.value.trim()
    if (!searchId) {
      currentMaterialPage.value = 1  // 重置页码
      fetchMaterialStocks()
      return
    }

    let response
    if (searchId.startsWith('INV')) {
      response = await inventoryAPI.material.getById(searchId)
    } else {
      response = await inventoryAPI.material.getByMaterialId(searchId)
    }

    if (response.data.code === 200) {
      const item = response.data.data
      materialStocks.value = [{
        id: item.inventoryId,
        materialId: item.materialId,
        materialName: item.materialName,
        quantity: item.quantity,
        safeStock: item.safetyStock || item.safeStock,
        unit: item.unit,
        updateTime: new Date().toLocaleString()
      }]
      totalMaterial.value = 1
    } else {
      ElMessage.error('未找到匹配的原料库存记录')
      materialStocks.value = [] // 清空表格数据
      totalMaterial.value = 0
    }
  } catch (error) {
    console.error('未找到匹配的原料库存记录')
    ElMessage.error('原料库存不存在')
    materialStocks.value = [] // 清空表格数据
    totalMaterial.value = 0
  } finally {
    loading.value = false
  }
}

// 重置产品搜索
const resetProductSearch = () => {
  productSearchQuery.value = ''
  currentProductPage.value = 1  // 重置产品页码
  fetchProductStocks()
}

// 重置原料搜索
const resetMaterialSearch = () => {
  materialSearchQuery.value = ''
  currentMaterialPage.value = 1  // 重置原料页码
  fetchMaterialStocks()
}

// 添加原料库存相关变量
const addMaterialDialogVisible = ref(false)
const addMaterialForm = ref({
  materialId: '',
  quantity: 0,
  unit: '',
  safetyStock: 0,
  description: ''
})

const materialOptions = ref([]) // 新增下拉框选项

// 添加原料库存方法
const addMaterialStock = async () => {
  if (!addMaterialForm.value.materialId) {
    ElMessage.warning('请选择原料')
    return
  }
  if (addMaterialForm.value.quantity <= 0) {
    ElMessage.warning('库存数量必须大于0')
    return
  }
  try {
    loading.value = true
    // 使用统一的API模块
    const response = await inventoryAPI.material.add(addMaterialForm.value)

    if (response.data.code === 200 && response.data.data === true) {
      ElMessage.success('原料库存添加成功')
      addMaterialDialogVisible.value = false
      fetchMaterialStocks() // 刷新原料库存列表
    } else {
      ElMessage.error(response.data.message || '添加原料库存失败')
    }
  } catch (error) {
    console.error('添加原料库存失败:', error)
    ElMessage.error(`添加原料库存失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const handleMaterialChange = (value) => {
  const selected = materialOptions.value.find(item => item.value === value)
  if (selected) {
    addMaterialForm.value = {
      ...addMaterialForm.value,
      materialId: selected.value,
      unit: selected.unit,
      description: selected.description,
      safetyStock: selected.safeStock
    }
  }
}

const showAddMaterialDialog = () => {
  addMaterialDialogVisible.value = true
  fetchMaterialOptions()
  // 重置表单时保留materialOptions
  addMaterialForm.value = {
    materialId: '',
    quantity: 0,
    unit: '',
    safetyStock: 0,
    description: ''
  }
}

const handleDeleteMaterial = async (inventoryId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条库存记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    // 使用统一的API模块
    const response = await inventoryAPI.material.delete(inventoryId)
    
    if (response.data.code === 200 && response.data.data === true) {
      ElMessage.success('删除成功')
      // 刷新数据
      fetchMaterialStocks()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除库存失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

const editDialogVisible = ref(false)
const editForm = ref({
  materialId: '',
  quantity: 0,
  reason: ''  // 新增原因字段
})

const showEditDialog = (row) => {
  editDialogVisible.value = true
  editForm.value = {
    materialId: row.materialId,
    quantity: 0,
    reason: ''  // 确保reason也被重置
  }
}

const handleReplenish = async () => {
  if (!editForm.value.reason) {
    ElMessage.warning('请填写补充原因')
    return
  }
  try {
    loading.value = true
    const params = {
      quantity: editForm.value.quantity,
      reason: editForm.value.reason
    }
    
    // 使用统一的API模块
    const response = await inventoryAPI.material.replenish(editForm.value.materialId, params)
    
    if (response.data.code === 200 && response.data.data === true) {
      ElMessage.success('库存补充成功')
      editDialogVisible.value = false
      fetchMaterialStocks()
    } else {
      const errorMsg = response.data.message || '库存补充失败'
      console.error('API错误响应:', response.data)
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error.response) {
      console.error('详细错误:', {
        status: error.response.status,
        data: error.response.data,
        headers: error.response.headers
      })
      ElMessage.error(`服务器错误: ${error.response.data?.message || '请检查数据格式'}`)
    } else {
      console.error('请求错误:', error.message)
      ElMessage.error(`请求失败: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

// Tab切换处理
const onTabChange = (tabName) => {
  console.log('切换到Tab:', tabName)
  if (tabName === 'material') {
    fetchMaterialStocks()
  } else if (tabName === 'product') {
    fetchProductStocks()
  }
}
</script>

<style scoped>
.stock-page {
  padding: 20px;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
}
</style>